import sys
import logging
from logging import handlers

import json
import time

import colorama

colorama.init(autoreset=True)

class Formatter(logging.Formatter):
    def __init__(self, fmt, args=None, datefmt=None, style='%'):
        self.args = args
        self.default_msec_format = '%s.%03d'
        logging.Formatter.__init__(self, fmt=fmt, datefmt=datefmt, style=style)
    def format(self, record):
        if self.args == None:
            return logging.Formatter.format(self, record)
        else:
            return  self.args[record.levelname]["prefix"] + \
                    logging.Formatter.format(self, record) + \
                    self.args[record.levelname]["suffix"]

class Logger:
    # 日志级别关系映射
    level_relations = {
        'DEBUG':logging.DEBUG,
        'INFO':logging.INFO,
        'WARNING':logging.WARNING,
        'ERROR':logging.ERROR,
        'CRITICAL':logging.CRITICAL
    }
    def __init__(self, args):
        # print(args)
        self.logger = logging.getLogger(args["name"])
        self.logger.setLevel(args["level"])
        # 初始化终端log
        # terminal = logging.StreamHandler(stream=sys.stdout) # 终端
        terminal = logging.StreamHandler() # 终端
        terminal.setFormatter(Formatter(args["terminal"]["fmt"], args["terminal"]["level-fmt"], args["terminal"]["datefmt"]))
        terminal.setLevel(self.level_relations.get(args["terminal"]["level"]))
        self.logger.addHandler(terminal)
        # 初始化文件log
        for filelog in args["output-file"]:
            # 往文件里写入#指定间隔时间自动生成文件的处理器
            # th = handlers.TimedRotatingFileHandler(filename=filelog["path"],when=filelog["when"],backupCount=filelog["backCount"],encoding='utf-8')
            th = logging.FileHandler(filename=filelog["path"],encoding='utf-8')
            th.setFormatter(Formatter(filelog["fmt"], datefmt=filelog["datefmt"]))
            th.setLevel(self.level_relations.get(filelog["level"]))
            self.logger.addHandler(th)

        self.debug = self.logger.debug
        self.info = self.logger.info
        self.warning = self.logger.warning
        self.error = self.logger.error
        self.critical = self.logger.critical

        self.info("log init")






